import { type Ref, ref } from 'vue'
import { useRouter } from 'vue-router'

import { roleApi } from '@/apis'
import { TableRefHook, useDialog } from '@/hooks'

import type { CheckedKeys } from '../types'
import { useRoleForm } from '.'

type Params = {
  checkedKeys: Ref<CheckedKeys>
  getMenuTree: PromiseFunc
  tableRefHook: TableRefHook
}

export function useOperation({
  checkedKeys,
  getMenuTree,
  tableRefHook
}: Params) {
  const selectedId = ref('')

  const router = useRouter()
  const { showConfirm } = useDialog()
  const {
    show: showEdit,
    loading: editLoading,
    formModel: editFormModel,
    formRef: editFormRef
  } = useRoleForm()

  function handleToggleStatus(item: any) {
    showConfirm({
      content: `确定${item.status === '0' ? '停用' : '启用'}角色？`,
      onOk: async () => {
        await roleApi.toggleRoleStatus(item.roleId)

        tableRefHook.refresh()
      },
      onCancel() {
        item.status = item.status === '0' ? '1' : '0'
      }
    })
  }

  function handleShowEdit(item: any) {
    const { roleId, menus, ...rest } = item
    selectedId.value = roleId
    editFormModel.value = rest
    checkedKeys.value.checked = menus.map(v => v.menuId)
    showEdit.value = true
    getMenuTree()
  }

  function handleCloseEdit() {
    showEdit.value = false
  }

  function handleEdit() {
    editFormRef.validate().then(async () => {
      try {
        editLoading.value = true

        await roleApi.updateRole(selectedId.value, {
          ...editFormModel.value,
          menus: [].concat(
            checkedKeys.value.halfChecked,
            checkedKeys.value.checked
          )
        })

        editLoading.value = true
        checkedKeys.value = {
          checked: [],
          halfChecked: []
        }
        handleCloseEdit()
        tableRefHook.refresh()
      } catch {
        editLoading.value = false
      }
    })
  }

  function handleAuthUser(id: string) {
    router.push({
      name: 'RoleAuthView',
      params: {
        id
      }
    })
  }

  function handleDelete(id: string) {
    showConfirm({
      content: '确认删除？',
      onOk: async () => {
        await roleApi.deleteRole({
          ids: [id]
        })

        tableRefHook.refresh()
      }
    })
  }

  return {
    showEdit,
    editLoading,
    editFormModel,
    editFormRef,
    handleToggleStatus,
    handleShowEdit,
    handleCloseEdit,
    handleEdit,
    handleAuthUser,
    handleDelete
  }
}
